import axios from "axios";

// 创建 axios 的实例对象
const axiosInstance = axios.create({
    baseURL: "/api",
    timeout: 5000
})
// 请求拦截器
axiosInstance.interceptors.request.use(
    config => {
        // 配置正常生成时
        const token = localStorage.getItem("token")
        if (token){
            // 添加密钥
            config.headers.token = token
        }
        return config
    },
    error => {
        // 配置生成错误时
        return Promise.reject(error)
    }
)
// 响应拦截器
axiosInstance.interceptors.response.use(
    res => {
        // 直接获取后端统一的JSON格式的data
        return res.data
    },
    error => {
        // 错误状态码异常时，非 2XX
        if (error.response?.status === 401) {
            localStorage.removeItem("token")
            localStorage.removeItem("user")
            location.href = "/login"
        }
        return Promise.reject(error)
    }
)
// 封装常用方法
export async function get(url, params) {
    try {
        // 键值对相同可直接省略键
        return await axiosInstance.get(url, {params})
    } catch (e) {
        throw new Error(e)
    }
}

export async function post(url, params){
    try {
        return await axiosInstance.post(url, params)
    }catch (e){
        throw new Error(e)
    }
}
